package com.anjufang.service.system.impl;

import com.anjufang.entity.AdminUser;
import com.anjufang.entity.AdminUserRole;
import com.anjufang.mapper.AdminUserMapper;
import com.anjufang.mapper.AdminUserRoleMapper;
import com.anjufang.service.system.AdminRoleService;
import com.anjufang.service.system.AdminUserService;
import com.anjufang.utils.StringUtils;
import com.anjufang.utils.page.Query;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class AdminUserServiceImpl implements AdminUserService {
	
	@Autowired
	private AdminRoleService userRoleService;
	@Autowired
	private AdminUserMapper adminUserMapper;
	@Autowired
	private AdminUserRoleMapper adminUserRoleMapper;
	
	@Override
	public List<AdminUser> queryList(Query query) {
		
		return adminUserMapper.queryList(query);
	}

	@Override
	public int queryTotal(Query query) {
		
		return adminUserMapper.queryTotal(query);
	}
	
	@Override
	public AdminUser getAdminUser(Long id) {
		
		return adminUserMapper.getUser(id);
	}
	
	@Override
	public AdminUser info(Long userId) {
		
		AdminUser user = adminUserMapper.selectById(userId);
		// 获取用户所属的角色列表
		List<AdminUserRole> roles = adminUserRoleMapper.selectList(new EntityWrapper<AdminUserRole>().where("user_id ={0}", userId));
		List<Long> roleIdList = new ArrayList<Long>();
		for (AdminUserRole AdminUserRole : roles) {
			roleIdList.add(AdminUserRole.getRoleId());
		}
		user.setRoleIdList(roleIdList);
		return user;
	}
	
	@Override
	public int selectCountByUserName(AdminUser user) {
		
		int count = adminUserMapper.selectCount(new EntityWrapper<AdminUser>().where("user_name={0}", user.getUserName()));
		return count;
	}
	
	@Override
	@Transactional
	public void save(AdminUser user) {
		user.setCreateTime(new Date());
		//sha256加密
		String salt = RandomStringUtils.randomAlphanumeric(20);
		user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
		user.setSalt(salt);
		adminUserMapper.insert(user);
		
		//保存用户与角色关系
		userRoleService.saveOrUpdate(user.getId(), user.getRoleIdList());
	}

	@Override
	@Transactional
	public void update(AdminUser user) {
		if(StringUtils.isBlank(user.getPassword())){
			user.setPassword(null);
		}else{
			user.setPassword(new Sha256Hash(user.getPassword(), user.getSalt()).toHex());
		}
		adminUserMapper.updateById(user);
		
		//保存用户与角色关系
		userRoleService.saveOrUpdate(user.getId(), user.getRoleIdList());
		
	}

}
